package net.siufung.core.utils;

import com.google.common.collect.Lists;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 笛卡尔乘积算法
 * @author 陈建峰
 * @since 2022/2/9 11:10 下午
 */
public class DescartesUtil {

    /**
     *  笛卡尔乘积算法
     * @param dimensionValue 原List
     * @param result 通过乘积转化后的数组
     * @param layer 中间参数
     * @param currentList 中间参数
     */
    public static <T> void descartes(List<List<T>> dimensionValue, List<List<T>> result, int layer, List<T> currentList){
        if (layer < dimensionValue.size() - 1) {
            if (CollectionUtils.isEmpty(dimensionValue.get(layer))) {
                descartes(dimensionValue, result, layer + 1, currentList);
            } else {
                for (int i = 0; i < dimensionValue.get(layer).size(); i++) {
                    List<T> list = new ArrayList<T>(currentList);
                    list.add(dimensionValue.get(layer).get(i));
                    descartes(dimensionValue, result, layer + 1, list);
                }
            }
        } else if (layer == dimensionValue.size() - 1) {
            if (CollectionUtils.isEmpty(dimensionValue.get(layer))) {
                result.add(currentList);
            } else {
                for (int i = 0; i < dimensionValue.get(layer).size(); i++) {
                    List<T> list = new ArrayList<T>(currentList);
                    list.add(dimensionValue.get(layer).get(i));
                    result.add(list);
                }
            }
        }
    }

    /**
     * 笛卡尔 计算
     * @param dimensionValue1 参数1
     * @param dimensionValue2 参数2
     * @return 笛卡尔集合
     */
    public static String[] descartes(String[] dimensionValue1, String[] dimensionValue2) {
        List<String> list = Lists.newArrayList();
        if (dimensionValue1.length == 0) {
            return dimensionValue2;
        }
        if (dimensionValue2.length == 0) {
            return dimensionValue1;
        }
        Arrays.stream(dimensionValue1).forEach(value1 -> {
            Arrays.stream(dimensionValue2).forEach(value2 -> {
                list.add(value1 + value2);
            });
        });
        return list.toArray(new String[0]);
    }
}
